import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/assets/images/avatar.jpg";
import { defineStore } from "pinia";
import useCallStore from "@/store/modules/call";

const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    userId: "",
    name: "",
    nickName: "",
    avatar: "",
    roles: [],
    permissions: [],
    deptId: "",
  }),
  getters: {
    // 定义的 getters，第一个参数就是该容器的 state
    // 判定当前角色是否是学生
    isStudent(state) {
      return state.roles.some((it) => it == "student");
    },
  },
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const deviceType = userInfo.deviceType;
      return new Promise((resolve, reject) => {
        login(username, password, deviceType)
          .then((res) => {
            setToken(res.token);
            this.token = res.token;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;
            const avatar =
              user.avatar === "" || user.avatar == null
                ? defAva
                : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles;
              this.permissions = res.permissions;
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            this.userId = user.userId;
            this.name = user.userName;
            this.nickName = user.nickName;
            this.avatar = avatar;
            this.deptId = user.deptId;
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    async logOut() {
      try {
        await useCallStore().disconnect();
      } catch (e) {}
      try {
        await logout(this.token);
        this.userId = "";
        this.nickName = "";
        this.token = "";
        this.roles = [];
        this.permissions = [];
        this.deptId = "";
        removeToken();
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },
  },
});

export default useUserStore;
